package com.common.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.FileItem;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import sun.misc.BASE64Decoder;


/**
 * 图片处理类
 * @author king
 *
 */
public class ImageUtil {
	
	
	
	
	public static String NGINXPATH = "D:/nginx/cloudRoot/Layui-SSM/";
	
	public static final int serverType = 0;// 1为负载均衡静态文件，0为单服务器

	
    /**
     * 存储base64图片
     *
     * @param imgStr
     * @param path
     * @return
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            File file = new File(path);
            if (!file.getParentFile().exists()) {// 先创建文件夹和文件
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	/**
	 * 处理上传的文件
	 * @param item
	 * @param filePath
	 * @param date
	 * @throws Exception
	 */
    public void processUploadFile(FileItem item, String filePath, String date)  throws Exception  {
		// 此时的文件名包含了完整的路径，得注意加工一下
		String filename = item.getName();

		int index = filename.lastIndexOf("\\");
		filename = filename.substring(index + 1, filename.length());
		long fileSize = item.getSize();
		if("".equals(filename) && fileSize == 0){
			return;
		}
		File file = new File(filePath + "/" + date+filename);
		if (!file.getParentFile().exists()){
			try {
				file.getParentFile().mkdirs();
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		item.write(file);
	}
    
    
    /**
     * 图片上传,并且自动压缩图片大小,图片大小超过100K自动按比例压缩到100K以下
     * @param item
     * @param filePath
     * @param filenames
     * @throws Exception
     */
    public static boolean processUploadFileGenerateSmall(FileItem item, String filePath,String filenames)  throws Exception  {  
    	boolean rs = true;
    	// 此时的文件名包含了完整的路径，得注意加工一下  
        String filename = item.getName();         
        int index = filename.lastIndexOf("\\");  
        filename = filename.substring(index + 1, filename.length());  
 
        long fileSize = item.getSize();  
        if("".equals(filename) && fileSize == 0){             
        	return false;
        }  
        File file = new File(filePath+"/"+filenames);  
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        File uploadFile = new File(filePath + "/" + filenames);  
        item.write(uploadFile);
        int kb = 100*1024;
        if(fileSize>100*1024){
        	int smallSize = (int) (fileSize%kb==0?fileSize/kb:fileSize/kb+1);
        	double size = Math.ceil(Math.sqrt(smallSize));
        	rs = ImageUtil.imageGenerateSmall(filePath + "/" + filenames, size);
        }
    	return rs;
    }
    
    /**
     * 图片上传,并且自动压缩添加水印
     * @param item
     * @param filePath
     * @param filenames
     * @throws Exception
     */
    public boolean processUploadFileByImage(FileItem item, String filePath,String filenames,int lastOid)  throws Exception  {  
    	// 此时的文件名包含了完整的路径，得注意加工一下  
    	String filename = item.getName();         
    	int index = filename.lastIndexOf("\\");  
    	filename = filename.substring(index + 1, filename.length());  
    	
    	long fileSize = item.getSize();  
    	if("".equals(filename) && fileSize == 0){             
    		return false;  
    	}  
    	File file = new File(filePath+"/"+lastOid);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	boolean rs = ImageUtil.imageSetSizeAndWatermark(400, 600, item.getInputStream(), filePath +"/"+lastOid+ "/" + filenames,filePath.replace("image","watermark")+"/"+lastOid+".png");
    	return rs;
    } 
    /**
     * 图片上传,并且自动压缩添加水印(整改照片)
     * @param item
     * @param filePath
     * @param filenames
     * @throws Exception
     */
    public boolean processUploadFileByImageUpdateImage(FileItem item, String filePath,String filenames,int lastOid)  throws Exception  {  
    	// 此时的文件名包含了完整的路径，得注意加工一下  
    	String filename = item.getName();         
    	int index = filename.lastIndexOf("\\");  
    	filename = filename.substring(index + 1, filename.length());  
    	
    	long fileSize = item.getSize();  
    	if("".equals(filename) && fileSize == 0){             
    		return false;  
    	}  
    	File file = new File(filePath+"/"+lastOid);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	boolean rs = ImageUtil.imageSetSizeAndWatermark(400, 600, item.getInputStream(), filePath +"/"+ filenames,filePath.replace("updateImage","watermark")+"/"+lastOid+".png");
    	return rs;
    }
	
	
	public static boolean imageSetSize(int height,int width,InputStream stream,String fileName){
		try {
			Thumbnails.of(stream).size(width, height).toFile(fileName);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	/**
	 * 缩放图片,并且加水印
	 * @param height
	 * @param width
	 * @param stream
	 * @param fileName
	 * @return
	 */
	public static boolean imageSetSizeAndWatermark(int width,int height,InputStream stream,String fileName,String watermarkName){
		try {
			File file = new File(watermarkName);
			if (file.exists()) {
				Thumbnails.of(stream)
				.size(width, height)
				.watermark(Positions.TOP_LEFT, ImageIO.read(file), 0.5f)
				.toFile(fileName);
			}else{
				Thumbnails.of(stream)
				.size(width, height)
				.toFile(fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 生成缩略图
	 * @param path 文件完整的路径
	 * @param smallSize 文件压缩倍数
	 * @return
	 */
	public static boolean imageGenerateSmall(String path, double smallSize){
		try {
			File bigFile = new File(path);
			Image image = ImageIO.read(bigFile);
			int width = image.getWidth(null);
			int height = image.getHeight(null);
			int widthSmall = (int) (width / smallSize);
			int heightSmall = (int) (height / smallSize);
			BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
			Graphics g = buffi.getGraphics();
			g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
			g.dispose();
			ImageIO.write(buffi, "jpg", new File(path));
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static void main(String[] args) {
		try {
			long fileSize = 4030464;
			int kb = 100*1024;
	        if(fileSize>100*1024){
	        	int smallSize = (int) (fileSize%kb==0?fileSize/kb:fileSize/kb+1);
	        	double size = Math.ceil(Math.sqrt(smallSize));
	        	System.out.println(size);
	        	boolean result = imageGenerateSmall("F:\\桌面资料\\IMG\\SFZZM1.jpg",size);
	        	System.out.println(result);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
